import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请检查手机号码是否正确!' },
    ],
    code: [
      { required: true, message: '请填写验证码!' },
      { pattern: /^\d{6}$/, message: '请检查验证码!' }
    ]
  },
  data: {
    countDownVisible: false,
    mobile: '',
    code: ''
  },
  onLoad(query) {
    // console.log(query);
    this.query = query

    // console.log(1);
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  async getSMScode() {
    const { valid, message } = this.validate('mobile')
    if (valid) {
      const res = await wx.http.get('/code', { mobile: this.data.mobile })
      console.log(res);
      wx.showToast({
        title: '验证码为' + res.data.code,
        icon: 'none',
        // duration: '3500'
      })
      this.setData({
        countDownVisible: true
      })
    } else {
      wx.utils.toast(message)
    }

  },
  async loginMethod() {
    const { mobile, code } = this.data

    const isTrue = this.validate()
    if (isTrue) {
      const res = await wx.http.post('/login', { mobile, code })
      // console.log(res);
      // 利用app中setToken方法存储token
      const app = getApp()
      app.setToken('token', res.data.token)
      // refreshToken用于续签
      app.setToken('refreshToken', res.data.refreshToken)
      // console.log('跳转URL:', this.query.redirectUrl);
      wx.redirectTo({
        url: this.query.redirectUrl,
      })

    }
  }
})
